package com.ddone;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * @author ddone
 * @date 2024/4/1-15:30
 */

public class JedisTest {

    private Jedis jedis;

    @Before
    public void init(){
        jedis = new Jedis("127.0.0.1", 6379);
    }

    @After
    public void destroy(){
        jedis.close();
    }

    @Test
    public void test(){
        String ddone = jedis.get("ddone");
        System.out.println(ddone);

        jedis.set("我爱你", "中国");

        Set<String> keys = jedis.keys("*");
        keys.forEach(System.out::println);

        System.out.println("jedis.get(\"我爱你\") = " + jedis.get("我爱你"));

        System.out.println(jedis.ping());

        jedis.lpush("list1","test1","test2","test3");
        List<String> list1 = jedis.lrange("list1", 0, 3);
        list1.forEach(System.out::println);

        jedis.sadd("sset","2","2","x","y","z");

        for (String key : keys) {
            String type = jedis.type(key);
            // 获取value的类型
            System.out.println(type);
        }

        Set<String> sset = jedis.smembers("sset");
        sset.forEach(System.out::println);
    }


    /**
     * 4)完成一个手机验证码功能
     * 要求:
     * 1、输入手机号，点击发送后随机生成6位数字码，2分钟有效
     * 2、输入验证码，点击验证，返回成功或失败
     * 3、每个手机号每天只能输入3次
     */
    @Test
    public void testCase(){
        //1.1获取客户端输入的手机号
        String mobile = "111000011";

        //2. 每个手机号每天只能输入3次
            //2.1 获取redis中当前手机号发送的次数
        String countKey = mobile+"_"+"cnt";
        String count = jedis.get(countKey);
        if(count == null){
            jedis.setex(countKey, 120, "1");
        } else {
            int countTimes = Integer.parseInt(count);
            if(countTimes >=3 ){
                jedis.close();
                System.out.println("验证码已发过三次");
            } else {
                jedis.incr(countKey);
            }
        }
        String code = getCode(6);
        System.out.println(code);
        String codeKey = mobile + "_" + code;
        jedis.setex(codeKey, 120, code);
    }

    private String getCode(int len){
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            int rand = random.nextInt(10);
            code.append(rand);
        }
        return code.toString();
    }

}
